import Vue from "vue";
import VueRouter from "vue-router";

import WrapperLayout from "./WrapperLayout";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    {
      path: "/",
      name: "/",
      redirect: "/home",
      component: WrapperLayout,
      children: [
        {
          path: "/home",
          name: "Home",
          component: () => import("@/views/home"),
        },
        {
          path: "/editor/:id",
          name: "Editor",
          component: () => import("@/views/editor"),
        },
      ],
    },
    {
      path: "/preview/:id",
      name: "Preview",
      component: () => import("@/views/preview"),
    },
    {
      path: "/monitor/:id",
      name: "Monitor",
      component: () => import("@/views/monitor"),
    },
    {
      path: "/login",
      name: "Login",
      component: () => import("@/views/Login.vue"),
    },
    {
      path: "*",
      name: "NotFound",
      component: () => import("@/views/NotFound.vue"),
    },
  ],
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    const token = sessionStorage.getItem("token");
    if (!token) {
      next("/login");
    } else {
      next();
    }
  }
});

export default router;
